package com.example.pay_service.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.example.pay_service.config.AlipayConfig;
import com.example.pay_service.service.ShoppingService;
import com.example.pay_service.vo.Order;
import com.example.pay_service.vo.Orders;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
@ResponseBody
@RequestMapping("/pay")
@Api
public class PayController {


    @Autowired
    ShoppingService shoppingService;


    private List list = new ArrayList();
    private List<Integer> list2 = new ArrayList();
    private static Map map = new  HashMap();

    @RequestMapping("pay")
    public void pay(Order order,HttpServletResponse response) {
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderId();
        System.out.println(out_trade_no);
        // 订单名称，必填
        String subject = order.getShopName();
        System.out.println(subject);
        // 付款金额，必填
        String total_amount=order.getShopPrice()+"";
        System.out.println(total_amount);
        // 商品描述，可空
        String body = order.getOrderDesc();
        System.out.println(body);
        // 超时时间 可空
        String timeout_express="2m";
        // 销售产品码 必填
        String product_code="QUICK_WAP_WAY";
        /**********************/

        Calendar calendar=Calendar.getInstance();//获得当前时间的月份，月份从0开始所以结果要加1
        int month=calendar.get(Calendar.MONTH)+1;
        long t=new Date().getTime();//获取当前时间戳
        String ordernumber=month+""+t; //订单编号 月份+用户id+时间戳
        Orders orders = new Orders();
        orders.setOrderid(ordernumber);
        orders.setUserid(1);


        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
//            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
      } catch (AlipayApiException | IOException e) {
          // TODO Auto-generated catch block
           e.printStackTrace();
        }

    }

    @RequestMapping("/notify_url")
    public void notify_url(){
        System.out.println("支付宝异步通知"+111111);
        for (int i = 0; i < list.size(); i++) {
            System.out.println("这是要修改的订单"+list.get(i));

        }
        if (list2.size()>0)
        for (int i = 0; i < list2.size(); i++) {
            System.out.println("这是要删除的购物车"+list2.get(i));
            shoppingService.delshopping(list2.get(i));

        }

        System.out.println("这是修改"+map.get("状态"));
        if (map.get("状态")!=null){
            if (map.get("状态").equals("结束")){
                System.out.println("清空");
                list=new ArrayList();
                list2=new ArrayList();
            }
        }

    }

    @RequestMapping("/return_url")
    public String return_url(){
        return "支付宝同步返回"+222222;
    }

//    //完成支付，写入数据库
//    @RequestMapping("/complete")
//    public void complete(HttpServletRequest request, HttpServletResponse response) {
//
//        //从session中获取定点信息
//        Order order=(Order)request.getSession().getAttribute("order");
//        System.out.println(order);
//        try {
//            //将数据插入到订单表中
//            payService.insertOrder(order);
//            response.sendRedirect(request.getContextPath()+"/payDemo.html");
//        } catch (Exception e) {
//            // TODO: handle exception
//            e.printStackTrace();
//        }
//
//    }

    @RequestMapping("addorder")
    public void addorder(Orders orders){
        System.out.println("这是状态"+orders.getState());
        System.out.println("这是购物车ID"+orders.getCart_id());
        if (orders.getState().equals("结束")){
            map.put("状态",orders.getState());
        }


        list.add(orders.getOrdernumber());
        list2.add(orders.getCart_id());
        System.out.println("这是生成的订单"+orders.getOrdernumber());
        System.out.println(orders.getUserid());
        System.out.println("这是商品ID"+orders.getSpid());
        System.out.println(orders.getPayway());
        System.out.println(orders.getLogisticscompany());
        System.out.println(orders.getOrderstatus());
        System.out.println(orders.getComitydescription());
        System.out.println(orders.getComityprices());
        System.out.println(orders.getComitynumber());
        System.out.println(orders.getComitypicture());
        System.out.println(orders.getSettlementprice());
        System.out.println(orders.getAddressinformation());
        System.out.println(orders.getFreight());
        System.out.println(orders.getActualpayment());
        System.out.println(orders.getPreferentialinformation());
        System.out.println(orders.getSpecifications());
    }

    public String getNowTime() {
        //格式化日期 pattern
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//HH24小时制、hh12小时制
        String eventDate;
        eventDate =  formatter.format(new Date());
        return eventDate;

    }

}

